package com.framework.dubbo.producer.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONObject;
import com.framework.dubbo.producer.service.Pdf2HtmlService;
import com.framework.dubbo.producer.utils.AlgorithmUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileFilter;
import java.net.URLEncoder;

@Slf4j
@RestController
@RequestMapping("/show")
public class Pdf2HtmlController {

    @Autowired
    private Pdf2HtmlService pdf2HtmlService;

    @Autowired
    private AlgorithmUtil algorithmUtil;

    @GetMapping("/version")
    public Object version() {
        return "1.0-SNAPSHOT";
    }

    /**
     * 获取配置信息
     * @return
     */
    @GetMapping("/config")
    public Object config() {
        return pdf2HtmlService.getPdf2HtmlProperties();
    }

    @PostMapping("/test")
    public Object test(@RequestBody JSONObject name) {
        return "params: " + name.toString();
    }

    /**
     * 获取并发信息
     * @return
     */
    @GetMapping("/metric")
    public Object metric() {
        return pdf2HtmlService.getMetric();
    }

    /**
     * 转换后下载全部
     * @param files
     * @param response
     */
    @PostMapping("/toHtmlAndDownloadZip")
    public void toHtmlAndDownloadZip(@RequestParam("files") MultipartFile[] files,
                         HttpServletResponse response) {
        if (ArrayUtil.isEmpty(files)) {
            log.warn("文件数为0");
            return;
        }
        File dir = null;
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            dir = pdf2HtmlService.pdf2html(files);

            // 将生成的html文件以及task.txt压缩, 并写入response
            ZipUtil.zip(outputStream, CharsetUtil.CHARSET_UTF_8, true, new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    if (pathname.isDirectory()) {
                        return true;
                    }
                    String name = pathname.getName().toLowerCase();
                    return name.endsWith(".html") || name.endsWith(".txt") || name.endsWith(".png")
                            || name.endsWith(".woff")|| name.endsWith(".css")|| name.endsWith(".ttf");
                }
            }, dir);

            response.addHeader("Content-Disposition",
                    "attachment;fileName=" + URLEncoder.encode(dir.getName() + ".zip", "UTF-8"));
            response.addHeader("Content-type", "application/zip");
        } catch (Throwable e) {
            log.error("pdf2html error", e);
        } finally {
            FileUtil.del(dir);
        }
    }

    /**
     * 转换后抽离图文并返回
     * @param file
     * @param response
     * @return
     */
    @PostMapping("/toSimpleHtml")
    public String toSimpleHtml(@RequestParam("file") MultipartFile file,
                         HttpServletResponse response) {
        if (file == null ||file.isEmpty()) {
            log.warn("文件为空");
            return null;
        }
        String context = null;
        try {
            context = pdf2HtmlService.pdf2html(file, false);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return context;
    }

    /**
     * 转换后原文件返回
     *  文件会非常大，不建议使用，只能用于解析小文件
     * @param file
     * @param response
     * @return
     */
    @PostMapping("/toFullHtml")
    public String toFullHtml(@RequestParam("file") MultipartFile file,
                         HttpServletResponse response) {

        if (file == null || file.isEmpty() ) {
            log.warn("文件为空");
            return null;
        }

        String context = null;
        try {
            context = pdf2HtmlService.pdf2html(file, true);
        } catch (Exception e) {
            e.printStackTrace();
        }

        /**
         * 文件太长
         */
        if (context.length() > 5000000){
            throw new RuntimeException("文件过大，请使用/show/toSimpleHtml方法");
        }
        return context;
    }


    /**
     * ocr测试
     * @param file
     * @param response
     * @return
     */
    @PostMapping("/fileToString")
    public String fileToString(@RequestParam("file") MultipartFile file,
                               HttpServletResponse response) {
        if (file == null ||file.isEmpty()) {
            log.warn("文件为空");
            return null;
        }
        String context = null;
        try {
            context = algorithmUtil.ocr(file.getInputStream(), file.getOriginalFilename());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return context;
    }
}
